import React, { useState, useEffect } from 'react';
import { Card } from '../../components/Card';
import { Toggle } from '../../components/Toggle';
import { Button } from '../../components/Button';
import { Modal } from '../../components/Modal';
import './RemindersTab.css';

export const RemindersTab = () => {
  const [reminders, setReminders] = useState([]);
  const [showAddModal, setShowAddModal] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadReminders();
    const interval = setInterval(updateTimers, 1000);
    return () => clearInterval(interval);
  }, []);

  const loadReminders = async () => {
    chrome.storage.local.get(['reminders'], (result) => {
      setReminders(result.reminders || []);
      setLoading(false);
    });
  };

  const updateTimers = () => {
    setReminders(prev => prev.map(reminder => ({ ...reminder })));
  };

  const calculateTimeUntilNext = (reminder) => {
    if (!reminder.enabled) return 'Disabled';
    if (!reminder.lastTriggered) return 'Starting...';
    
    const now = Date.now();
    const frequencyMs = reminder.frequency * 60 * 1000;
    const nextTriggerTime = reminder.lastTriggered + frequencyMs;
    const timeRemaining = nextTriggerTime - now;
    
    if (timeRemaining <= 0) return 'Due now';
    
    const hours = Math.floor(timeRemaining / (1000 * 60 * 60));
    const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);
    
    if (hours > 0) return `${hours}h ${minutes}m`;
    if (minutes > 0) return `${minutes}m ${seconds}s`;
    return `${seconds}s`;
  };

  const formatFrequency = (frequency) => {
    if (frequency >= 1440) return 'Daily';
    if (frequency >= 60) return `Every ${frequency / 60} ${frequency / 60 === 1 ? 'hour' : 'hours'}`;
    return `Every ${frequency} ${frequency === 1 ? 'minute' : 'minutes'}`;
  };

  const handleToggle = async (reminderId, enabled) => {
    const updatedReminders = reminders.map(r =>
      r.id === reminderId
        ? { ...r, enabled, lastTriggered: enabled && !r.lastTriggered ? Date.now() : r.lastTriggered }
        : r
    );
    await chrome.storage.local.set({ reminders: updatedReminders });
    setReminders(updatedReminders);
  };

  const handleAddReminder = async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const newReminder = {
      id: `custom-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      title: formData.get('title'),
      description: formData.get('description') || '',
      frequency: parseInt(formData.get('frequency')) || 60,
      enabled: formData.get('enabled') === 'on',
      custom: true,
      icon: '⏰',
      category: 'Custom',
      lastTriggered: null
    };

    const updatedReminders = [...reminders, newReminder];
    await chrome.storage.local.set({ reminders: updatedReminders });
    setReminders(updatedReminders);
    setShowAddModal(false);
    e.target.reset();
  };

  if (loading) {
    return <div className="loading">Loading reminders...</div>;
  }

  return (
    <div className="reminders-tab">
      <div className="section-header">
        <h2>Reminders</h2>
        <Button onClick={() => setShowAddModal(true)}>+ Add</Button>
      </div>

      {reminders.length === 0 ? (
        <div className="empty-state">
          <p>No reminders configured. Add one to get started!</p>
        </div>
      ) : (
        <div className="reminders-list">
          {reminders.map((reminder) => (
            <Card key={reminder.id} className="reminder-item">
              <div className="reminder-header">
                <h3>
                  <span>{reminder.icon || '⏰'}</span>
                  {reminder.title}
                </h3>
                <Toggle
                  checked={reminder.enabled}
                  onChange={(e) => handleToggle(reminder.id, e.target.checked)}
                />
              </div>
              {reminder.description && (
                <p className="reminder-description">{reminder.description}</p>
              )}
              <div className="reminder-footer">
                <span className="frequency">{formatFrequency(reminder.frequency)}</span>
                <span className="reminder-timer">{calculateTimeUntilNext(reminder)}</span>
              </div>
            </Card>
          ))}
        </div>
      )}

      <Modal isOpen={showAddModal} onClose={() => setShowAddModal(false)} title="Add Custom Reminder">
        <form onSubmit={handleAddReminder}>
          <div className="form-group">
            <input type="text" name="title" placeholder="Title" required />
          </div>
          <div className="form-group">
            <textarea name="description" placeholder="Description" rows="2"></textarea>
          </div>
          <div className="form-group">
            <label>
              Frequency (minutes):
              <input type="number" name="frequency" min="1" defaultValue="60" required />
            </label>
          </div>
          <div className="form-group">
            <label>
              <input type="checkbox" name="enabled" defaultChecked /> Enable immediately
            </label>
          </div>
          <Button type="submit">Add Reminder</Button>
        </form>
      </Modal>
    </div>
  );
};

